/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.six.paneles.opciones;

import com.sig.utilerias.entity.EntityManagerFactory;
import com.six.dto.GcliInfProblemaMedico;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.NotifyDescriptor.Confirmation;

final class ProblemasMedicosPanel extends javax.swing.JPanel {

    private final ProblemasMedicosOptionsPanelController controller;
    private final MyListener listener = new MyListener();
    private int idProblema = -1;

    ProblemasMedicosPanel(ProblemasMedicosOptionsPanelController controller) {
        this.controller = controller;
        initComponents();
        // TODO listen to changes in form fields and call controller.changed()
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtProblemasMedicos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jtfProblemaMedico = new javax.swing.JTextField();

        setPreferredSize(new java.awt.Dimension(300, 300));

        jPanel1.setPreferredSize(new java.awt.Dimension(600, 300));

        jtProblemasMedicos.setModel(new ProblemasMedicosPanel.MyModel());
        jtProblemasMedicos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtProblemasMedicos);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/six/paneles/opciones/resources/agregar.png"))); // NOI18N
        jButton1.setToolTipText(org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jButton1.text")); // NOI18N
        jButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jButton1.setPreferredSize(new java.awt.Dimension(40, 40));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/six/paneles/opciones/resources/aceptar.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jButton2.text")); // NOI18N
        jButton2.setToolTipText(org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jButton2.text")); // NOI18N
        jButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jButton2.setPreferredSize(new java.awt.Dimension(40, 40));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jLabel1.text")); // NOI18N

        jtfProblemaMedico.setDocument(new com.sig.utilerias.text.JTextFieldLimit(100));
        jtfProblemaMedico.setText(org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jtfProblemaMedico.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfProblemaMedico)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(242, 242, 242)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfProblemaMedico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void setFields(int index) {
        GcliInfProblemaMedico gipm = ((MyModel) jtProblemasMedicos.getModel()).getValueAt(index);
        this.idProblema = gipm.getIdProblema();
        this.jtfProblemaMedico.setText(gipm.getDescProblema());
    }

    private void clearFields() {
        this.idProblema = -1;
        this.jtfProblemaMedico.setText("");
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        clearFields();
        this.jtfProblemaMedico.requestFocus();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Logger.getLogger(ProblemasMedicosPanel.class.getName()).warning("Guardar problema médico");

        if (jtfProblemaMedico.getText() != null && !"".equals(jtfProblemaMedico.getText())) {
            EntityManager em = EntityManagerFactory.getEntityManager();
            if (em == null) {
                Confirmation message = new NotifyDescriptor.Confirmation("Error en la base de datos!!",
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(message);
                return;
            }

            EntityTransaction transaction = em.getTransaction();
            try {
                transaction.begin();
                TypedQuery<GcliInfProblemaMedico> query = em.createNamedQuery("GcliInfProblemaMedico.findByIdProblema", GcliInfProblemaMedico.class);
                query.setParameter("idProblema", this.idProblema);
                List<GcliInfProblemaMedico> list = query.getResultList();
                GcliInfProblemaMedico problemaMedico;

                System.out.println("Size::" + list.size());
                if (list.size() > 0) {
                    problemaMedico = list.get(0);
                } else {
                    problemaMedico = new GcliInfProblemaMedico();
                }
                problemaMedico.setDescProblema(jtfProblemaMedico.getText());
                GcliInfProblemaMedico merge = em.merge(problemaMedico);
                transaction.commit();
                recargarTabla(em);
                idProblema = merge.getIdProblema();
            } catch (Exception e) {
                Confirmation message = new NotifyDescriptor.Confirmation("Error al guardar problema m\u00e9dico. ERROR:: " + e.getMessage(),
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(message);
                Logger.getLogger(ProblemasMedicosPanel.class.getName()).log(Level.SEVERE, "Error al guardar problema m\u00e9dico. ERROR:: {0}", e.getMessage());
            }
        } else {
            Confirmation message = new NotifyDescriptor.Confirmation("Problema Médico no puede estar vacio, favor de verificar!!",
                    NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notify(message);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    void load() {
        Logger.getLogger(ProblemasMedicosPanel.class.getName()).warning("Se cargan los problemas médicos a la tabls");
        EntityManager em = EntityManagerFactory.getEntityManager();
        this.idProblema = -1;

        if (em == null) {
            Confirmation message = new NotifyDescriptor.Confirmation("Error en la base de datos!!",
                    NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notify(message);
            return;
        }
        recargarTabla(em);
    }

    private void recargarTabla(EntityManager em) {
        final TypedQuery<GcliInfProblemaMedico> query = em.createNamedQuery("GcliInfProblemaMedico.findAll", GcliInfProblemaMedico.class);
        System.out.println("Inicia" + new Date());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.out.println("Inicia:RUN:" + new Date());
                jtProblemasMedicos.getSelectionModel().removeListSelectionListener(listener);
                @SuppressWarnings("unchecked")
                List<GcliInfProblemaMedico> problemasMedicos = query.getResultList();
                if (problemasMedicos != null && !problemasMedicos.isEmpty()) {
                    MyModel modelo = (MyModel) jtProblemasMedicos.getModel();
                    modelo.addRows(problemasMedicos);
                }
                jtProblemasMedicos.getSelectionModel().addListSelectionListener(listener);
                System.out.println("Fin:RUN:" + new Date());
            }
        });
        System.out.println("fin" + new Date());
    }

    void store() {
        // TODO store modified settings
        // Example:
        // Preferences.userNodeForPackage(ProblemasMedicosPanel.class).putBoolean("someFlag", someCheckBox.isSelected());
        // or for org.openide.util with API spec. version >= 7.4:
        // NbPreferences.forModule(ProblemasMedicosPanel.class).putBoolean("someFlag", someCheckBox.isSelected());
        // or:
        // SomeSystemOption.getDefault().setSomeStringProperty(someTextField.getText());
    }

    boolean valid() {
        // TODO check whether form is consistent and complete
        return true;
    }

    private class MyListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.err.println("ListSelectionEvent" + e);
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();

            if (lsm.isSelectionEmpty()) {
                Logger.getLogger(ProblemasMedicosPanel.class.getName()).log(Level.SEVERE, "Sin datos");
            } else {
                int seleccionIndex = lsm.getMinSelectionIndex();
                System.err.println("SeleccionIndex::" + seleccionIndex);
                setFields(seleccionIndex);
            }
        }
    }

    private class MyModel extends AbstractTableModel implements Serializable {

        private final List<GcliInfProblemaMedico> problemaMedico = new ArrayList<GcliInfProblemaMedico>();

        public void addRows(List<GcliInfProblemaMedico> problemaMedico) {
            this.problemaMedico.clear();
            this.problemaMedico.addAll(problemaMedico);
            fireTableRowsInserted(0, this.problemaMedico.size());
        }

        @Override
        public String getColumnName(int column) {
            return org.openide.util.NbBundle.getMessage(ProblemasMedicosPanel.class, "ProblemasMedicosPanel.jtProblemasMedicos.columnModel.title0");
        }

        @Override
        public int getRowCount() {
            return problemaMedico.size();
        }

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return problemaMedico.get(rowIndex).getDescProblema();
        }

        private GcliInfProblemaMedico getValueAt(int index) {
            if (index < this.problemaMedico.size()) {
                return this.problemaMedico.get(index);
            }
            return null;
        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtProblemasMedicos;
    private javax.swing.JTextField jtfProblemaMedico;
    // End of variables declaration//GEN-END:variables
}
